package java_class.student2_class;

public class Test {
    public static void main(String[] args) {
        student[] arr=new student[3];

        student stu1=new student("孙亚森",22,001);
        student stu2=new student("李晴",22,002);
        student stu3=new student("张三",22,003);

        arr[0]=stu1;
        arr[1]=stu2;
        arr[2]=stu3;

        student stu4=new student("李四",12,004);
        // 判断学号是否存在
        if(contains(arr,stu4.getId())){
            System.out.println("此学号已经存在 请换一个新的学号");
        }else{
        // 判断数组长度够不够
            int count=getCount(arr);
            if(count==arr.length){
        // 数组满了 构建创建新的数组的方法
                student[] newArr=setNewArr(arr);
                newArr[count]=stu4;
                printArr(newArr);
            }else{
        //  数组没满 直接添加
                arr[count]=stu4;
                printArr(arr);
            }
        }

    }
    public static void printArr(student[] arr){
        for (int i = 0; i < arr.length; i++) {
            if(arr[i]!=null){
                System.out.println(arr[i].getId()+" "+arr[i].getName()+" "+arr[i].getAge());

            }
        }
    }
    public static student[] setNewArr(student[] arr){
        student newArr[]=new student[arr.length+1];
        for (int i = 0; i < arr.length; i++) {
            newArr[i]=arr[i];
        }
        return newArr;
    }
    public static int getCount(student[] arr){
        //  获取数组中不是null的个数
        int count=0;
        for (int i = 0; i < arr.length; i++) {
            if(arr[i]!=null){
                count++;
            }
        }
        return count;
    }
    public static boolean contains(student[] arr,int id){
        for (int i = 0; i < arr.length; i++) {
            if(arr[i]!=null){
                if(arr[i].getId()==id){
                    return true;
                }
            }

        }
        return false;
    }
}
